/**$Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *   Copyright (C) 2008 - 2013 xingsheng.zhu@gmail.com All rights reserved.
 */
package com.blazemina.robot.connector;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.blazemina.config.BlazeminaConfigManager;
import com.blazemina.message.Message;
import com.blazemina.mina.Connector;
import com.blazemina.mina.config.SocketOption;
import com.blazemina.mina.protocol.amf.AmfCodecFactory;

/**
 * @author JackChu
 * @version 1.0.0 2013-3-4 下午12:50:53
 */
public class MinaConnector implements Connector {
	
	private IoSession session;

	public void init() {

	}

	public void start() {
		// Create TCP/IP connection
		NioSocketConnector connector = new NioSocketConnector();

		DefaultIoFilterChainBuilder chain = connector.getFilterChain();

		chain.addLast("codec", new ProtocolCodecFilter(new AmfCodecFactory()));

		// 服务器的消息处理器：一个SamplMinaServerHander对象
		connector.setHandler(BlazeminaConfigManager.me().getRequestHandler());

		SocketOption socketOption = BlazeminaConfigManager.me().getSocketOption();
		String host = socketOption.getHost();
		int port = socketOption.getPort();
		// 连接到服务器：
		ConnectFuture cf = connector.connect(new InetSocketAddress(host, port));

		// Wait for the connection attempt to be finished.
		cf.awaitUninterruptibly();
		
		session = cf.getSession();

	}

	public void stop() {

	}
	
	public void send(Message message){
		session.write(message);
	}

}
